import React, { useRef, useState } from 'react';
import { Avatar, message } from 'antd';
import { connect } from 'dva';
import './comment.css';
import { getFilePrefix } from '../../../utils/config';
import { LikeFilled, DislikeOutlined, LikeOutlined, DislikeFilled } from '@ant-design/icons';

function Item({
  item,
  handleLiked,
  handleDisLiked,
  handleSubmit,
  isChild,
  onToggleReply,
  activeInputId,
  setActiveInputId,
  isLogin,
  isAdmin
}) {
  const [inputValue, setInputValue] = useState('');

  const handleReplyClick = () => {
    if (!isLogin) {
      message.error('请先登录');
      return;
    }
    if (isAdmin) {
      message.error('管理员不能回复');
      return;
    }
    setActiveInputId(activeInputId === item.commentId ? null : item.commentId);
    setInputValue('');
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleSubmitClick = () => {
    if (inputValue.trim() === '') {
      message.error('请输入评论内容');
      return;
    }
    handleSubmit(item.commentId, inputValue);
    setActiveInputId(null);
    setInputValue('');
  };

  return (
    <div className={isChild ? "reply-item child" : "reply-item"}>
      <div className="root-reply-avatar">
        <Avatar size={isChild ? 30 : 45} src={item.filePath === "" ? "/image/login/defaultFilePath.png" : getFilePrefix() + item.filePath} />
      </div>
      <div className="content-wrap">
        <div className="user-info">
          <div className="user-name">
            {item.parentDisplayName === "" ? item.displayName :
              (<>
                {item.displayName}
                <span className="reply-spacing">回复:</span>
                {item.parentDisplayName}
              </>)}
          </div>
        </div>
        <div className="root-reply">
          <span className="reply-content">{item.content}</span>
          <div className="reply-info">
            <span className="reply-time">{item.createTime}</span>
            <span className="reply-time" onClick={() => handleLiked(item.commentId, item.isLiked)}>
              {item.isLiked ? <LikeFilled style={{ color: 'red' }} /> : <LikeOutlined />}
              {item.like}
            </span>
            <span className="reply-time" onClick={() => handleDisLiked(item.commentId, item.isDisLiked)}>
              {item.isDisLiked ? <DislikeFilled style={{ color: 'red' }} /> : <DislikeOutlined />}
              {item.disLike}
            </span>
            <span className="delete-btn" onClick={handleReplyClick}>回复</span>
          </div>
          {item.children.length > 0 && (
            <div className='reply-info'>
              <span className="toggle-reply" onClick={() => onToggleReply(item.commentId)}>
                {item.showReplies ? "收起回复" : "展开回复"}
              </span>
            </div>
          )}
          {activeInputId === item.commentId && (
            <div className="reply-box-wrap">
              <input
                type="text"
                className="reply-box-textarea"
                value={inputValue}
                onChange={handleInputChange}
                placeholder={"回复 " + item.displayName}
              />
              <div className="reply-box-send">
                <div className="send-text" onClick={handleSubmitClick}>发布</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

const Comment = ({ dispatch, commentList, articleDetail, userInfo }) => {
  const [content, setContent] = useState('');
  const [expandedIds, setExpandedIds] = useState([]); // 使用数组来追踪展开的评论ID
  const [activeInputId, setActiveInputId] = useState(null);
  const inputRef = useRef(null);
  const isLogin = userInfo && userInfo.userId > 0;
  const isAdmin = userInfo && userInfo.userType === 0;

  const handleAction = (type, payload) => {
    if (!isLogin) {
      message.error('请先登录');
      return;
    }
    if (isAdmin) {
      message.error('管理员不能操作');
      return;
    }
    dispatch({ type, payload });
  };

  const handleToggleReply = (commentId) => {
    const currentIndex = expandedIds.indexOf(commentId);
    const newExpandedIds = [...expandedIds];
    if (currentIndex === -1) {
      newExpandedIds.push(commentId);
    } else {
      newExpandedIds.splice(currentIndex, 1);
    }
    setExpandedIds(newExpandedIds);
  };

  const handleLiked = (commentId, isLike) => {
    handleAction('articleDetail/likeComment', {
      userId: userInfo.userId,
      commentId,
      isLike: !isLike
    })
  };

  const handleDisLiked = (commentId, isDisLike) => {
    handleAction('articleDetail/disLikeComment', {
      userId: userInfo.userId,
      commentId,
      isDisLike: !isDisLike
    })
  };

  const handleSubmit = (commentParentId, inputValue) => {
    handleAction('articleDetail/addComment', {
      userId: userInfo.userId,
      articleId: articleDetail.articleId,
      content: inputValue,
      commentParentId
    });
  };

  const handlePublish = () => {
    if (content.trim() === '') {
      message.error('请输入评论内容');
      return;
    }
    handleSubmit(0, content);
    setContent('');
    inputRef.current && inputRef.current.focus();
  };

  return (
    <div className="app">
      <div className="reply-wrap">
        <div className="box-normal">
          <div className="reply-box-wrap">
            <textarea
              className="reply-box-textarea"
              placeholder="发一条友善的评论"
              ref={inputRef}
              value={content}
              onChange={(e) => setContent(e.target.value)}
            />
            <div className="reply-box-send">
              <div className="send-text" onClick={handlePublish}>发布</div>
            </div>
          </div>
        </div>
        <div className="reply-list">
          {commentList.map(parentItem => (
            <React.Fragment key={parentItem.commentId}>
              <Item
                item={{ ...parentItem, showReplies: expandedIds.includes(parentItem.commentId) }}
                handleLiked={handleLiked}
                handleDisLiked={handleDisLiked}
                handleSubmit={handleSubmit}
                onToggleReply={handleToggleReply}
                activeInputId={activeInputId}
                setActiveInputId={setActiveInputId}
                isLogin={isLogin}
                isAdmin={isAdmin}
              />
              {expandedIds.includes(parentItem.commentId) && parentItem.children && (
                <div>
                  {parentItem.children.map(childItem => (
                    <Item
                      key={childItem.commentId}
                      item={childItem}
                      handleLiked={handleLiked}
                      handleDisLiked={handleDisLiked}
                      isChild={true}
                      handleSubmit={handleSubmit}
                      activeInputId={activeInputId}
                      setActiveInputId={setActiveInputId}
                      isLogin={isLogin}
                      isAdmin={isAdmin}
                    />
                  ))}
                </div>
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
};

export default connect(({ articleDetail, user }) => ({
  userInfo: user.userInfo,
  articleDetail: articleDetail.articleDetail,
  commentList: articleDetail.commentList,
}))(Comment);